package com.tudouji.project.harvest.service.impl;

import com.tudouji.common.utils.BigDecimalUtils;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.harvest.domain.*;
import com.tudouji.project.harvest.mapper.ContstandardMapper;
import com.tudouji.project.harvest.mapper.FreightorderMapper;
import com.tudouji.project.harvest.mapper.ProcurementcontractMapper;
import com.tudouji.project.harvest.mapper.QaresultMapper;
import com.tudouji.project.harvest.service.IQaresultService;
import com.tudouji.project.quality.domain.Qaitems;
import com.tudouji.project.quality.domain.Qamain;
import com.tudouji.project.quality.domain.Qarecord;
import com.tudouji.project.quality.mapper.QamainMapper;
import com.tudouji.project.quality.mapper.QarecordMapper;
import com.tudouji.project.quality.service.impl.QarecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 质检结果Service业务层处理
 *
 * @author tudouji
 * @date 2021-05-13
 */
@Service
public class QaresultServiceImpl implements IQaresultService {
    @Autowired
    private QaresultMapper qaresultMapper;
    @Autowired
    private ProcurementcontractMapper procurementcontractMapper;
    @Autowired
    private QamainMapper qamainMapper;
    @Autowired
    private QarecordServiceImpl qarecordService;
    @Autowired
    private QarecordMapper qarecordMapper;
    @Autowired
    private ContstandardMapper contstandardMapper;
    @Autowired
    private FreightorderMapper freightorderMapper;

    /**
     * 查询质检结果
     *
     * @param id 质检结果ID
     * @return 质检结果
     */
    @Override
    public Qaresult selectQaresultById(Long id) {
        return qaresultMapper.selectQaresultById(id);
    }

    @Override
    public List<Qaresult> selectQaresultByLinkId(String foguid) {
        return qaresultMapper.selectQaresultByLinkId(foguid);
    }

    /**
     * 查询质检结果列表
     *
     * @param qaresult 质检结果
     * @return 质检结果
     */
    @Override
    public List<Qaresult> selectQaresultList(Qaresult qaresult) {
        return qaresultMapper.selectQaresultList(qaresult);
    }

    /**
     * 新增质检结果
     *
     * @param qaresult 质检结果
     * @return 结果
     */
    @Override
    public int insertQaresult(Qaresult qaresult) {
        return qaresultMapper.insertQaresult(qaresult);
    }

    /**
     * 修改质检结果
     *
     * @param qaresult 质检结果
     * @return 结果
     */
    @Override
    public int updateQaresult(Qaresult qaresult) {
        return qaresultMapper.updateQaresult(qaresult);
    }

    /**
     * 批量删除质检结果
     *
     * @param ids 需要删除的质检结果ID
     * @return 结果
     */
    @Override
    public int deleteQaresultByIds(Long[] ids) {
        return qaresultMapper.deleteQaresultByIds(ids);
    }

    /**
     * 删除质检结果信息
     *
     * @param id 质检结果ID
     * @return 结果
     */
    @Override
    public int deleteQaresultById(Long id) {
        return qaresultMapper.deleteQaresultById(id);
    }

    @Override
    public AjaxResult getQaResultWithType(String guid, Integer type) {
        Qaresult qaresult = new Qaresult();
        qaresult.setFoguid(guid);
        qaresult.setType(type);
        BigDecimal qaResult = qaresultMapper.selectQaresultByLinkIdDF(qaresult);
        return AjaxResult.success(qaResult);
    }


    /**
     * @return
     * @Author shaodong
     * @Description //5最终结算单价计算规则
     * 5.1统一扣杂法
     * 假设采收合同规定的扣杂率为 rc,质检单扣杂率为 rq，合同单价为pc
     * 1、根据合同扣杂率扣杂： 结算单价 = pc * （1-rc）
     * 2、根据质检结果扣杂：结算单价 = pc * ( 1 – rq )
     * 3、合同和质检结果取最大： 结算单价 =  pc * [1 – max (rq , rc)]
     * 5.2分步扣杂法
     * 假设合格规定的合格薯单价为pc，淀粉薯单价为pu。
     * 5.2.1按照质检结果分步扣杂
     * 假设 土杂率 rc,不合格率 ru, 则 结算单价 = rc * pc + ru * pu
     * 5.2.2优质优价
     * 1、质检合格
     * 假设根据质检结果计算的合计奖励金额为 pb, 扣罚金额为 pf
     * 结算单价 = pc + pb - pf
     * 2、质检不合格
     * 质检不合格需要录入淀粉薯含量，假设根据淀粉薯含量计算的奖励金额为pb，扣罚金额为pf（pb、pf必有一项为0），则：
     * 结算金额 = pu + pb - pf
     * @Date 9:35 2021/3/12
     * @Param QA_RESULT=2: 不合格
     **/
    public void calculateRatend(Freightorder freightorder, Qaform qaform) {
        BigDecimal deductrate = BigDecimal.ZERO;
        Procurementcontract contract = procurementcontractMapper.selectProcurementcontractById(freightorder.getContractid());

        BigDecimal rHand = freightorder.getDeductRateByHand() == null ? BigDecimal.ZERO : freightorder.getDeductRateByHand();
        BigDecimal rc = contract.getDiscountrate() == null ? BigDecimal.ZERO : contract.getDiscountrate();
        BigDecimal rq = qaform == null ? BigDecimal.ZERO : qaform.getDeductrate();

        Freightorder order = new Freightorder();

        if (rHand.compareTo(BigDecimal.ZERO) == 1) {
            deductrate = rHand;
        } else {
            if (freightorder.getIsdiscount() == 1) { //1-按合同扣杂,2-按质检单扣杂,3-就高扣杂
                //1-按合同扣杂
                deductrate = rc;
            }
            if (freightorder.getIsdiscount() == 2) {//isdiscount=4的时候是分级扣杂标准，还是按照质检单扣杂
                // 2-按质检单扣杂
                if (qaform == null) {
                    deductrate = BigDecimal.ZERO;
                } else {
                    deductrate = rq;
                }
            }
            if (freightorder.getIsdiscount() == 3) {
                // 3-就高扣杂
                deductrate = rc.compareTo(rq) == 1 ? rc : rq;

            }

            if (freightorder.getIsdiscount() == 4) {
                if (rHand.compareTo(BigDecimal.ZERO) == 1) {
                    deductrate = rHand;
                } else {
                    if (qaform == null) {
                        deductrate = BigDecimal.ZERO;
                    } else {
                        deductrate = rq;
                    }
                }
            }

            /***
             *分布扣杂--扣杂标准为5是原分布扣杂的方式
             */
            if (freightorder.getIsdiscount() == 5) {
                // freightorder.getDeducttype() == 2     分布扣杂
                // 最终杂土率 = MAX（质检单土杂率，合同约定土杂率 ）
                // 20190823 修改为: 最终杂土率 =   MAX（质检单土杂率，货运单土杂率 ）
                BigDecimal dustDeductionRate = /*geRateMax(*/qaform.getSoilchkrate()/*, freightorder.getSoilchkrate())*/;

                //获得最终不合格率  =  质检单不合格率 - 合同约定不合格率 （大于0有效）
                // 20190823 修改为: 获得最终不合格率  =  质检单不合格率 - 货运单约定不合格率 （大于0有效）
                BigDecimal flawDeductionRate = /*getFlawDeductionRate(*/qaform.getUnqualifiedchkrate()/*, freightorder.getUnqualifiedchkrate())*/;

                //扣杂率 = 获得最终不合格率   + 最终杂土率
                if (rHand.compareTo(BigDecimal.ZERO) == 1) {
                    deductrate = rHand;
                } else {
                    deductrate = dustDeductionRate.add(flawDeductionRate);
                }

            }
        }

        order.setGuid(freightorder.getGuid());
        order.setRatend(deductrate);
        freightorderMapper.updateFreightorder(order);
    }


    /**
     * @return
     * @Author shaodong
     * @Description //5最终结算单价计算规则
     * 5.1统一扣杂法
     * 假设采收合同规定的扣杂率为 rc,质检单扣杂率为 rq，合同单价为pc
     * 1、根据合同扣杂率扣杂： 结算单价 = pc * （1-rc）
     * 2、根据质检结果扣杂：结算单价 = pc * ( 1 – rq )
     * 3、合同和质检结果取最大： 结算单价 =  pc * [1 – max (rq , rc)]
     * 5.2分步扣杂法
     * 假设合格规定的合格薯单价为pc，淀粉薯单价为pu。
     * 5.2.1按照质检结果分步扣杂
     * 假设 土杂率 rc,不合格率 ru, 则 结算单价 = rc * pc + ru * pu
     * 5.2.2优质优价
     * 1、质检合格
     * 假设根据质检结果计算的合计奖励金额为 pb, 扣罚金额为 pf
     * 结算单价 = pc + pb - pf
     * 2、质检不合格
     * 质检不合格需要录入淀粉薯含量，假设根据淀粉薯含量计算的奖励金额为pb，扣罚金额为pf（pb、pf必有一项为0），则：
     * 结算金额 = pu + pb - pf
     * @Date 9:35 2021/3/12
     * @Param QA_RESULT=2: 不合格
     **/
    public BigDecimal calculateSinglePrice(Freightorder freightorder, Qaform qaform, int QA_RESULT, List<Qaresult> qaresults
            , BigDecimal price, BigDecimal unitPrice, Integer flag) {//flag=1:修改合同单价，flag=2修改淀粉单价
        BigDecimal settlPrice = BigDecimal.ZERO;
        Freightorder order = new Freightorder();

        Procurementcontract contract = procurementcontractMapper.selectProcurementcontractById(freightorder.getContractid());
        Qamain qamain = qamainMapper.selectQamainById(contract.getQamainid());
        List<Contstandard> contstandards = contstandardMapper.selectContstandardByContractid(freightorder.getContractid());
        BigDecimal deductrate = freightorder.getRatend();
        BigDecimal rHand = freightorder.getDeductRateByHand() == null ? BigDecimal.ZERO : freightorder.getDeductRateByHand();
        BigDecimal pc = contract.getPrice();//合同薯单价
        if (2 == qamain.getType()) {
            if (1 == flag && price != null) {
                pc = price;
            }
            /*2022.03.01 淀粉属统一扣杂，先生成qaresult,计算出淀粉含量，才可以计算合同价*/
            if (2 == flag && unitPrice != null) {
                System.out.println("****************unitPrice:" + unitPrice);
                if ((freightorder.getIsdiscount() == 1 || freightorder.getIsdiscount() == 2 || freightorder.getIsdiscount() == 3)) {
                    if (null == unitPrice) {
                        unitPrice = order.getUnitPrice();
                    }
                    Qaresult qaresult  = new Qaresult();
                    qaresult.setFoguid(freightorder.getGuid());
                    qaresult.setType(4);
                    BigDecimal itemResult = qaresultMapper.selectQaresultByLinkIdDF(qaresult);
                    BigDecimal dfPrice = itemResult.multiply(unitPrice)
                            .setScale(2, BigDecimal.ROUND_HALF_DOWN);
                    order.setUnitPrice(unitPrice);
                    order.setPrice(dfPrice);
                    pc = dfPrice;
                }
            }
        }

        BigDecimal pu = BigDecimal.ZERO;
        /**
         * 2022.03.01淀粉薯采收修改合同单价
         */
        for (int i = 0; i < contstandards.size(); i++) {
            Contstandard con = contstandards.get(i);
            if (2 == con.getType()) {//1-土杂 2-不合格项 3-普通合格项 4-淀粉薯含量, 不合格项按照淀粉薯采收
                pu = con.getPrice();
            }
        }

        if (rHand.compareTo(BigDecimal.ZERO) == 1) {
            settlPrice = pc.multiply(BigDecimal.ONE.subtract(deductrate.divide(new BigDecimal(100))));
        } else {
            if (freightorder.getIsdiscount() == 1 || freightorder.getIsdiscount() == 2 ||
                    freightorder.getIsdiscount() == 3 || freightorder.getIsdiscount() == 4) {
                settlPrice = pc.multiply(BigDecimal.ONE.subtract(deductrate.divide(new BigDecimal(100))));
            }

            /***
             *分布扣杂--扣杂标准为5是原分布扣杂的方式
             */
            if (freightorder.getIsdiscount() == 5) {
                // freightorder.getDeducttype() == 2     分布扣杂
                // 最终杂土率 = MAX（质检单土杂率，合同约定土杂率 ）
                // 20190823 修改为: 最终杂土率 =   MAX（质检单土杂率，货运单土杂率 ）
                BigDecimal dustDeductionRate = /*geRateMax(*/qaform.getSoilchkrate()/*, freightorder.getSoilchkrate())*/;

                //获得最终不合格率  =  质检单不合格率 - 合同约定不合格率 （大于0有效）
                // 20190823 修改为: 获得最终不合格率  =  质检单不合格率 - 货运单约定不合格率 （大于0有效）
                BigDecimal flawDeductionRate = /*getFlawDeductionRate(*/qaform.getUnqualifiedchkrate()/*, freightorder.getUnqualifiedchkrate())*/;

                //假设 土杂率 rc,不合格率 ru, 则 结算单价 = rc * pc + ru * pu
                settlPrice = (BigDecimal.ONE.subtract(dustDeductionRate.divide(new BigDecimal(100)))
                        .subtract(flawDeductionRate.divide(new BigDecimal(100)))).multiply(pc)
                        .add(flawDeductionRate.divide(new BigDecimal(100)).multiply(pu));
            }

            /**
             * @Author shaodong
             * @Description 优质优价扣杂法
             * @Date 13:46 2021/3/11
             * @Param
             * @return
             **/
            if (freightorder.getIsdiscount() == 6) {
                if (2 == QA_RESULT) {
                    settlPrice = pu;
                    for (int i = 0; i < qaresults.size(); i++) {
                        Qaresult qaresult = qaresults.get(i);
                        if (4 == qaresult.getType()) {
                            BigDecimal pb = qaresult.getAwardamount();
                            BigDecimal pf = qaresult.getDeductamount();
                            settlPrice = settlPrice.add(pb).subtract(pf);
                            System.out.println(settlPrice + "=" + pu + "+" + pb + "-" + pf);
                        }
                    }
                } else if (1 == QA_RESULT) {//商品薯：合格的情况下，不将淀粉薯含量奖罚计算进单价
                    settlPrice = pc;
                    for (int i = 0; i < qaresults.size(); i++) {
                        Qaresult qaresult = qaresults.get(i);
                        if (4 == qaresult.getType() && qamain.getType() == 1) {
                            continue;
                        }
                        BigDecimal pb = qaresult.getAwardamount();
                        BigDecimal pf = qaresult.getDeductamount();
                        settlPrice = settlPrice.add(pb == null ? BigDecimal.ZERO : pb)
                                .subtract(pf == null ? BigDecimal.ZERO : pf);
                    }
                }
                settlPrice = settlPrice.multiply(BigDecimal.ONE.subtract(qaform.getSoilchkrate().divide(new BigDecimal(100))));
            }
        }

        order.setGuid(freightorder.getGuid());
        order.setActualSettl(settlPrice);
        freightorderMapper.updateFreightorder(order);
        System.out.println("结算单价为： " + settlPrice);
        return settlPrice;
    }

    public int setQaresult(Freightorder order, String userid/*, BigDecimal unitPrice*/) {
        Procurementcontract contract = procurementcontractMapper.selectProcurementcontractById(order.getContractid());
        Qamain qamain = qamainMapper.selectQamainById(contract.getQamainid());
        String orderid = order.getGuid();
        delRestult(orderid);
        int QA_RESULT = 1;
        boolean HAVE_DF = false;//没有录入淀粉含量
        List<Qaresult> qaresults = new ArrayList<>();
        List<Qaitems> qaitems = qarecordService.getQaItemsMain(order);
        Qarecord record = getCordSum(orderid);
        int recordSize = qarecordMapper.selectQarecordListCount(orderid);

        for (int i = 0; i < qaitems.size(); i++) {
            Qaitems qaitem = qaitems.get(i);

            Qaresult qaresult = new Qaresult();
            qaresult.setFoguid(orderid);
            qaresult.setCreatedate(new Date());
            qaresult.setOperatorid(userid);
            qaresult.setQaitemid(qaitem.getGuid());
            qaresult.setQaitemname(qaitem.getItemname());
            if (3 == qaitem.getQaflag()) {//普通合格项
                qaresult.setQaitemresult(
                        calculateQaitemresult(record.getTotalweightsum(), record.getItemWeight(i), qaitem.getDataType(), recordSize));//质检结果	0~100%
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);        //合格	1-是 2-否
                qaresult.setAwardamount(calculateAwardAmount(qaitem, qaresult));      //奖励金额
                qaresult.setDeductamount(calculateDeductAmount(qaitem, qaresult));     //扣罚金额
            } else if (2 == qaitem.getQaflag()) {//普通不合格项
                qaresult.setQaitemresult(
                        calculateQaitemresult(record.getTotalweightsum(), record.getItemWeight(i), qaitem.getDataType(), recordSize));//质检结果	0~100%
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);        //合格	1-是 2-否
                qaresult.setAwardamount(calculateAwardAmount(qaitem, qaresult));      //奖励金额
                qaresult.setDeductamount(calculateDeductAmount(qaitem, qaresult));     //扣罚金额
            } else if (4 == qaitem.getQaflag()) {//淀粉含量
                HAVE_DF = BigDecimal.ZERO.compareTo(record.getItemWeight(i)) == -1 ? true : false;
                qaresult.setQaitemresult(
                        calculateQaitemresult(record.getTotalweightsum(), record.getItemWeight(i), qaitem.getDataType(), recordSize));
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);
                qaresult.setAwardamount(calculateAwardAmount(qaitem, qaresult));
                qaresult.setDeductamount(calculateDeductAmount(qaitem, qaresult));
            } else if (1 == qaitem.getQaflag()) {//土杂含量
                qaresult.setQaitemresult(
                        calculateQaitemresult(record.getTotalweightsum(), record.getItemWeight(i), qaitem.getDataType(), recordSize));
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);
                qaresult.setAwardamount(BigDecimal.ZERO);      //奖励金额
                qaresult.setDeductamount(BigDecimal.ZERO);     //扣罚金额

            } else if (5 == qaitem.getQaflag()) {//干物质
                qaresult.setQaitemresult(
                        calculateQaitemresult(record.getTotalweightsum(), record.getItemWeight(i), qaitem.getDataType(), recordSize));
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);
                qaresult.setAwardamount(calculateAwardAmount(qaitem, qaresult));
                qaresult.setDeductamount(calculateDeductAmount(qaitem, qaresult));

            } else if (6 == qaitem.getQaflag()) {//GAP 0-否 1-是
                qaresult.setQaitemresult(getCordSmall("item" + (i + 1) + "weight", orderid));
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);
                qaresult.setAwardamount(calculateAwardAmount(qaitem, qaresult));
                qaresult.setDeductamount(calculateDeductAmount(qaitem, qaresult));

            } else if (7 == qaitem.getQaflag()) {//轮作年数
                BigDecimal re = getCordSmall("item" + (i + 1) + "weight", orderid);
                qaresult.setQaitemresult(re);
                qaresult.setQualified(isQualified(qaitem, qaresult) ? 1 : 2);
                qaresult.setAwardamount(calculateAwardAmount(qaitem, qaresult));
                qaresult.setDeductamount(calculateDeductAmount(qaitem, qaresult));

            }

            if (2 == qaresult.getQualified() && 4 != qaitem.getQaflag() && qamain.getType() == 1) {//商品薯-淀粉含量不作为最终结果的判断条件
                QA_RESULT = 2;
            }
            if (2 == qaresult.getQualified() && qamain.getType() == 2) {//淀粉薯-淀粉含量不作为最终结果的判断条件
                QA_RESULT = 2;
            }
            qaresults.add(qaresult);
            qaresultMapper.insertQaresult(qaresult);
        }
        if (QA_RESULT == 2 && !HAVE_DF) {//不合格的情况下，淀粉录入含量等于零时
            QA_RESULT = 4;
        }
        return QA_RESULT;
    }

    private void delRestult(String orderid) {
        List<Qaresult> delQaresults = qaresultMapper.selectQaresultByLinkId(orderid);
        if (delQaresults.size() > 0) {
            Long[] ids = new Long[delQaresults.size()];
            for (int i = 0; i < delQaresults.size(); i++) {
                ids[i] = delQaresults.get(i).getId();
            }
            qaresultMapper.deleteQaresultByIds(ids);
        }
    }

    /**
     * @return
     * @Author shaodong
     * @Description //汇总
     * @Date 16:23 2021/3/23
     * @Param
     **/
    private Qarecord getCordSum(String orderguid) {
        return qarecordService.findItemSum(orderguid);
    }

    /**
     * @return
     * @Author shaodong
     * @Description 计算质检结果
     * @Date 16:50 2021/3/10
     * @Param
     **/
    private BigDecimal calculateQaitemresult(BigDecimal totalweight, BigDecimal itemwight, Integer dataType, int recordSize) {
        if (itemwight == null) {
            itemwight = new BigDecimal(0);
        }
        if (1 == dataType) {
            return BigDecimalUtils.formatBigDecimal(itemwight.divide(totalweight, 5, BigDecimal.ROUND_HALF_UP), 4).multiply(new BigDecimal(100));
        } else if (2 == dataType) {
            return BigDecimalUtils.formatBigDecimal(itemwight.divide(new BigDecimal(recordSize), 5, BigDecimal.ROUND_HALF_UP), 4);
        }
        return BigDecimal.ZERO;
    }

    /**
     * @return 合格: true-是 false-否'
     * @Author shaodong
     * @Description 是否合格
     * @Date 16:50 2021/3/10
     **/
    private boolean isQualified(Qaitems qa, Qaresult result) {
        boolean unqualified = true;
        BigDecimal qaitemresult = result.getQaitemresult();

        Integer unqualifiedchecktype = qa.getUnqualifiedchecktype();
        if (null == unqualifiedchecktype) {
            return unqualified;
        }
        BigDecimal unqualifiedcheckvalue = qa.getUnqualifiedcheckvalue();
        if (1 == unqualifiedchecktype) {//>=
            if (qaitemresult.compareTo(unqualifiedcheckvalue) > -1) {
                return unqualified = false;
            }
        } else if (2 == unqualifiedchecktype) {//>
            if (qaitemresult.compareTo(unqualifiedcheckvalue) == 1) {
                return unqualified = false;
            }
        } else if (3 == unqualifiedchecktype) {//<=
            if (qaitemresult.compareTo(unqualifiedcheckvalue) < 1) {
                return unqualified = false;
            }
        } else if (4 == unqualifiedchecktype) {//<
            if (qaitemresult.compareTo(unqualifiedcheckvalue) == -1) {
                return unqualified = false;
            }
        } else if (5 == unqualifiedchecktype) {//=
            if (qaitemresult.compareTo(unqualifiedcheckvalue) == 0) {
                return unqualified = false;
            }
        }
        return /*qualified && */unqualified;
    }

    /**
     * @return
     * @Author shaodong
     * @Description 计算奖励金额
     * @Date 16:50 2021/3/10
     **/
    private BigDecimal calculateAwardAmount(Qaitems qa, Qaresult result) {
        BigDecimal resultValue = BigDecimal.ZERO;
        BigDecimal maxvalue = qa.getMaxRewards();//最大奖励金额
        BigDecimal qaitemresult = result.getQaitemresult();
        Integer rewardchecktype = qa.getRewardchecktype();
        if (null == rewardchecktype) {
            return resultValue;
        }
        BigDecimal rewardcheckvalue = qa.getRewardcheckvalue();
        BigDecimal rewardcheckstep = qa.getRewardcheckstep();
        BigDecimal rewardvalue = qa.getRewardvalue() == null ? BigDecimal.ZERO : qa.getRewardvalue();
        if (BigDecimal.ZERO.compareTo(rewardcheckstep) == 0) {//0：固定奖励，不递进
            if (1 == rewardchecktype) {//>=
                if (qaitemresult.compareTo(rewardcheckvalue) > -1) {
                    return rewardvalue;
                }
            } else if (2 == rewardchecktype) {//>
                if (qaitemresult.compareTo(rewardcheckvalue) == 1) {
                    return rewardvalue;
                }
            } else if (3 == rewardchecktype) {//<=
                if (qaitemresult.compareTo(rewardcheckvalue) < 1) {
                    return rewardvalue;
                }
            } else if (4 == rewardchecktype) {//<
                if (qaitemresult.compareTo(rewardcheckvalue) == -1) {
                    return rewardvalue;
                }
            } else if (5 == rewardchecktype) {//=
                if (qaitemresult.compareTo(rewardcheckvalue) == 0) {
                    return rewardvalue;
                }
            }
            return BigDecimal.ZERO;
        } else {
            if (1 == rewardchecktype) {//>=
                if (qaitemresult.compareTo(rewardcheckvalue) > -1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }
                }
            } else if (2 == rewardchecktype) {//>
                if (qaitemresult.compareTo(rewardcheckvalue) == 1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }
                }
            } else if (3 == rewardchecktype) {//<=
                if (qaitemresult.compareTo(rewardcheckvalue) < 1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }
                }
            } else if (4 == rewardchecktype) {//<
                if (qaitemresult.compareTo(rewardcheckvalue) == -1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }
                }
            } else if (5 == rewardchecktype) {//=
                if (qaitemresult.compareTo(rewardcheckvalue) == 0) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }// n：以n为步长递进奖励，目前n=1
                }
            }
            return resultValue;
        }
    }

    /**
     * @return
     * @Author shaodong
     * @Description 计算扣罚金额
     * @Date 16:50 2021/3/10
     * @Param
     **/
    private BigDecimal calculateDeductAmount(Qaitems qa, Qaresult result) {
        BigDecimal resultValue = BigDecimal.ZERO;
        BigDecimal qaitemresult = result.getQaitemresult();
        Integer rewardchecktype = qa.getPunisheschecktype();
        if (null == rewardchecktype) {
            return resultValue;
        }
        BigDecimal rewardcheckvalue = qa.getPunishescheckvalue();
        BigDecimal rewardcheckstep = qa.getPunishescheckstep();
        BigDecimal rewardvalue = qa.getPunishesvalue() == null ? BigDecimal.ZERO : qa.getPunishesvalue();
        BigDecimal maxvalue = qa.getMaxPunishes();//最大扣罚金额
        if (BigDecimal.ZERO.compareTo(rewardcheckstep) == 0) {//0：固定奖励，不递进
            if (1 == rewardchecktype) {//>=
                if (qaitemresult.compareTo(rewardcheckvalue) > -1) {
                    return rewardvalue;
                }
            } else if (2 == rewardchecktype) {//>
                if (qaitemresult.compareTo(rewardcheckvalue) == 1) {
                    return rewardvalue;
                }
            } else if (3 == rewardchecktype) {//<=
                if (qaitemresult.compareTo(rewardcheckvalue) < 1) {
                    return rewardvalue;
                }
            } else if (4 == rewardchecktype) {//<
                if (qaitemresult.compareTo(rewardcheckvalue) == -1) {
                    return rewardvalue;
                }
            } else if (5 == rewardchecktype) {//=
                if (qaitemresult.compareTo(rewardcheckvalue) == 0) {
                    return rewardvalue;
                }
            }
            return BigDecimal.ZERO;
        } else {
            if (1 == rewardchecktype) {//>=
                if (qaitemresult.compareTo(rewardcheckvalue) > -1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }
                }
            } else if (2 == rewardchecktype) {//>
                if (qaitemresult.compareTo(rewardcheckvalue) == 1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }// n：以n为步长递进奖励，目前n=1
                }
            } else if (3 == rewardchecktype) {//<=
                if (qaitemresult.compareTo(rewardcheckvalue) < 1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }// n：以n为步长递进奖励，目前n=1
                }
            } else if (4 == rewardchecktype) {//<
                if (qaitemresult.compareTo(rewardcheckvalue) == -1) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }// n：以n为步长递进奖励，目前n=1
                }
            } else if (5 == rewardchecktype) {//=
                if (qaitemresult.compareTo(rewardcheckvalue) == 0) {
                    resultValue = rewardvalue.multiply(qaitemresult
                            .subtract(rewardcheckvalue)
                            .divide(rewardcheckstep)
                            .abs().setScale(2));
                    if (null != maxvalue) {
                        return resultValue.compareTo(maxvalue) > -1 ? maxvalue : resultValue;
                    }// n：以n为步长递进奖励，目前n=1
                }
            }
            return resultValue;
        }
    }

    /**
     * @return
     * @Author shaodong
     * @Description //取最小值
     * @Date 16:23 2021/3/23
     * @Param
     **/
    private BigDecimal getCordSmall(String itemAny, String orderguid) {
        Qarecord qarecord = new Qarecord();
        qarecord.setFoguid(orderguid);
        qarecord.setKey(itemAny);
        qarecord = qarecordMapper.getCordSmall(qarecord);
        if (null == qarecord) {
            return BigDecimal.ZERO;
        }
        return qarecord.getItemsamllweight();
    }
}
